package com.agentframework.examples.jinhua;

import com.agentframework.core.agent.Agent;
import com.agentframework.core.environment.EnvironmentEventListener;
import com.agentframework.core.environment.EnvironmentStartedEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.messages.UserMessage;

import java.util.List;
import java.util.Set;

import static com.agentframework.core.agent.Agent.ACTION;
import static com.agentframework.core.agent.Agent.SEND_TO;

/**
 * @author wangjun
 **/
public class JinhuaStarted implements EnvironmentEventListener<EnvironmentStartedEvent> {

    protected static final Logger logger = LoggerFactory.getLogger(JinhuaStarted.class);

    @Override
    public void onEnvironmentEvent(EnvironmentStartedEvent event) {
        JinhuaEnvironment environment = (JinhuaEnvironment) event.getEnvironment();
        List<Agent> playerAgents = environment.getJinhuaGameState().getPlayerAgents();

        logger.debug("JinhuaStarted 玩家： {}", playerAgents);

        // 荷官
        Agent dealerAgent = environment.getJinhuaGameState().getDealerAgent();
        dealerAgent.getContext().addWatches(playerAgents.stream().map(Agent::getAgentId).toList());
        dealerAgent.getContext().addWatch(dealerAgent.getAgentId());

        logger.debug("JinhuaStarted 荷官： {}", dealerAgent);

        // 为玩家设置订阅荷官消息
        playerAgents.forEach(player -> player.getContext().addWatch(dealerAgent.getAgentId()));

        UserMessage userMessage = new UserMessage("游戏开始");
        userMessage.getMetadata().put(SEND_TO, Set.of(dealerAgent.getAgentId()));
        userMessage.getMetadata().put(ACTION, "start_new_round");
        environment.publishMessage(userMessage);
    }

}
